using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class GameItemBox : MonoBehaviour
{
    public Camera sceneCamera;
    public Image imageItem;
    public Toggle toggleItem;
    public static GameItemBox Instance;
    private void Awake()
    {
        Instance = this;
        imageItem.gameObject.SetActive(false);
    }

    Coroutine _coroutine;
    public void MoveImageItem(int itemTypeId, GameObject triggerGameObject)
    {
        if(_coroutine != null)
        {
            StopCoroutine(_coroutine);
        }
        var configItem = ConfigItem.GetElement(itemTypeId);
        var spriteName = ConfigItemHelper.GetSpriteName(configItem);
        XRes.LoadAsset<Sprite>(spriteName, (sprite) =>
        {
            imageItem.sprite = sprite;
            imageItem.SetNativeSize();
            XRes.ReleaseAsset(sprite);
        });
        var viewPort = sceneCamera.WorldToViewportPoint(triggerGameObject.transform.position);

        //临时代码，需要重构
        Vector3 pos = new Vector3();
        pos.x = (viewPort.x - 0.12f)* 750f;
        pos.y = viewPort.y * 1134;

        _coroutine = StartCoroutine(CoMoveImageItem(pos));
    }

    private IEnumerator CoMoveImageItem(Vector3 fromPos)
    {
        imageItem.gameObject.SetActive(true);
        toggleItem.isOn = true;
        float time = 1;
        float distance = Vector3.Distance(fromPos, Vector3.zero);
        for (float i = 0; i < time; i += Time.deltaTime)
        {
            imageItem.transform.localPosition = Vector3.MoveTowards(fromPos, Vector3.zero, distance * i / time);
            yield return null;
        }
        //imageItem.transform.localPosition = Vector3.zero;
        imageItem.gameObject.SetActive(false);
        toggleItem.isOn = false;
        _coroutine = null;
    }
}
